package router

import (
	"fmt"
	"math/rand"
	"net/http"
	"vue-gin/handlers"
	"github.com/gin-gonic/gin"
)

func PrintMiddleware(c *gin.Context) {
	fmt.Println("before request")
	c.Next()
}

func ValidateToken() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.FormValue("token")
		if token == "" {
			c.JSON(401, gin.H{"message": "Token required"})
			c.Abort()
			return
		}
		if token != "accesstoken" {
			c.JSON(http.StatusOK, gin.H{"message": "Invalid Token"})
			c.Abort()
			return
		}
		c.Next()
	}
}

func Init() {
	// Creates a default gin router
	r := gin.Default()
	r.Use(PrintMiddleware) //注意: 这里是一个函数名
	r.LoadHTMLGlob("templates/*")

	api := r.Group("/api")
	{
		api.GET("/hello", handlers.HelloPage)
		api.GET("/hello/:name", func(c *gin.Context) {
			name := c.Param("name")
			c.String(http.StatusOK, "Hello %s", name)
		})
		api.GET("/welcome", func(c *gin.Context){
			firstname := c.DefaultQuery("firstname", "Guest")
			lastname := c.Query("lastname")
			c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
		})
		api.GET("/line", func(c *gin.Context){
			legendData := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
			xAxisData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
			c.JSON(200, gin.H{
				"legend_data": legendData,
				"xAxis_data": xAxisData})
		})
	}


	// Grouping routes, // group： v1
	v1 := r.Group("/v1")
	{
		v1.GET("/hello", handlers.HelloPage)
		v1.GET("/hello/:name", func(c *gin.Context) {
			name := c.Param("name")
			c.String(http.StatusOK, "Hello %s", name)
		})
		v1.GET("/welcome", func(c *gin.Context){
			firstname := c.DefaultQuery("firstname", "Guest")
			lastname := c.Query("lastname")
			c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
		})
		v1.GET("/line", func(c *gin.Context){
			legendData := []string{"周一", "周二", "周三", "周四", "周五", "周六", "周日"}
			xAxisData := []int{120, 240, rand.Intn(500), rand.Intn(500), 150, 230, 180}
			c.JSON(200, gin.H{
				"legend_data": legendData,
				"xAxis_data": xAxisData})
		})
	}
	
	v2 := r.Group("/v2")
	{	
		v2.Use(ValidateToken())
		v2.GET("/index", func(c *gin.Context) {
			c.HTML(http.StatusOK, "index.html", gin.H{"title":"Hello Gin"})
		})
	}
	

	r.NoRoute(func(c *gin.Context){
		c.JSON(http.StatusNotFound, gin.H{
			"status": 404,
			"error": "404, page not found"})
	})
	r.Run(":8001")
}


